package tech.aistar.util.WxNew;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import sun.net.www.protocol.http.HttpURLConnection;
import tech.aistar.entity.Wx.Article;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取每天的新闻
 */
public class GetNew {
    public static  List<Article>  getNewOneDay() {

        String url="http://api.tianapi.com/bulletin/?key=ec07b37d6506f3a611320c1d2964130a";
        StringBuffer sbf = new StringBuffer();
        List<Article> list=new ArrayList<>();
        try {
            URL realUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            BufferedReader  reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            String jsonResult = sbf.toString();
            JSONObject  jsonObj = JSONObject.fromObject(jsonResult);

            JSONArray jsonIndex = jsonObj.getJSONArray("newslist");

            for(int i=0;i<jsonIndex.size();i++){
                JSONObject partDaily = jsonIndex.getJSONObject(i);
                Article article=  new Article();
                article.setDigest(partDaily.getString("digest"));
                article.setMtime(partDaily.getString("mtime"));
                article.setSource(partDaily.getString("source"));
                article.setTitle(partDaily.getString("title"));
                list.add(article);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
